<template>
  <div class="container">
    <n-page-header title="创建新话题" @back="toBack" />
    <div class="form">
      <n-input v-model:value="form.title"
               placeholder="在这里输入话题标题"
               type="text"
               maxlength="30"
               show-count
      />
      <n-input v-model:value="form.content"
               :autosize="{minRows: 5}"
               placeholder="话题内容"
               type="textarea"
               maxlength="2000"
               show-count
      />
      <n-button type="primary" @click="createTopic" :loading="requesting" :disabled="requesting">创建</n-button>
    </div>
  </div>
</template>

<script setup>
import {useRouter} from "vue-router";
import {useRequests} from "@/common/requests.js";
import {ref} from "vue";
import {useMessage, useNotification} from "naive-ui";

const router = useRouter()
const requests = useRequests()
const message = useMessage()
const notify = useNotification()

const toBack = () => {
  router.back()
}

const form = ref({
  title: null,
  content: null
})
const requesting = ref(false)
const createTopic = () => {
  if (form.value.title == null || form.value.title.length === 0) {
    message.error("标题不能为空")
  } else if (form.value.content == null || form.value.content.length < 50) {
    message.error("话题内容不能小于50个字符")
  } else {
    requesting.value = true
    requests.topic.new(form.value).then(resp => {
      requesting.value = false
      if (resp.ret === 0) {
        form.value = {
          title: null,
          content: null
        }

        router.back()
        message.success("创建成功")
      } else {
        message.error(resp?.data ?? resp?.msg ?? '未知错误')
      }
    }).catch(err => {
      requesting.value = false

      console.log(err)
      notify.error({content: '出错了', meta: err.toString(), duration: 1500})
    })
  }
}
</script>

<style lang="scss" scoped>
.container {
  .form {
    margin-top: 1.5rem;

    .n-input {
      margin-bottom: 1rem;
    }
  }
}
</style>
